import React,{memo,useEffect,useRef,useCallback,useState} from 'react'
import {useSelector,useDispatch,shallowEqual} from 'react-redux'
import {getTopBannersAction} from '../../store/actionCreators'

import {WrapperContainer,BannerRight,BannerLeft,BannerControl} from './style'
import { Carousel } from 'antd';
export default memo(function TopBanner(){
    //state 
    const [currentIndex, setCurrentIndex] = useState()

    //组件和redux关联 ：获取数据和进行操作
    const recommend = useSelector(state => ({
        topBanners:state.getIn(["recommend","topBanners"])
    }),shallowEqual)
    const dispatch = useDispatch()

    //其他hook
    //hook 中ref用法 1.先定义
    const bannerRef = useRef()
    // shallowEqual优化将里面对象进行浅层比较
    useEffect(() => {
        dispatch(getTopBannersAction())
    }, [dispatch])
    //当给组件传入一个函数时用useCallback可以做缓存
    const bannerChange = useCallback(
        (from,to) => {
            //to可以拿到下一页的index
            // console.log(to);
            setCurrentIndex(to)
        },
        []
    )

    //其他业务逻辑
    const bgImage = recommend.topBanners[currentIndex] &&  recommend.topBanners[currentIndex].imageUrl+'?imageView&blur=40x20'
    return (
        <WrapperContainer bgImage={bgImage}>
            <div className='wrap-v2'>
                <BannerLeft>
                    {/* 将定义的名字引用到轮播图 */}
                    <Carousel ref={bannerRef} effect="fade" autoplay beforeChange={bannerChange}>
                    {
                        recommend.topBanners.map((item,index)=>{
                            return (
                                <div className='banner-item' key={item.imageUrl}>
                                    <img src={item.imageUrl}/>
                                </div>
                            )
                        })
                    }
                    
                </Carousel>
                </BannerLeft>
                <BannerRight></BannerRight>
                <BannerControl>
                    {/* prev和next为走马灯上下页切换的方法 */}
                    <div className='btnLeft' onClick={(e)=>bannerRef.current.prev()}></div>
                    <div className='btnRight' onClick={(e)=>bannerRef.current.next()}></div>
                </BannerControl>
            </div>
        </WrapperContainer>
    )
})
